package cn.tedu.boot.ers.controller;


import cn.tedu.boot.ers.config.Constant;
import cn.tedu.boot.ers.entity.Product;
import cn.tedu.boot.ers.exception.ServiceException;
import cn.tedu.boot.ers.pojo.dto.AddProductDTO;
import cn.tedu.boot.ers.pojo.dto.UpdateProductDTO;
import cn.tedu.boot.ers.service.ProductService;
import cn.tedu.boot.ers.web.JsonResult;
import cn.tedu.boot.ers.web.State;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * @Description: 后台商品管理Controller
 * @Author: han
 * @Date: 2022/6/11
 **/
@Slf4j
@Api(tags = "商品管理模块")
@RestController
@RequestMapping("/admins")
public class ProductAdminController {

    @Autowired
    ProductService productService;

    @ApiOperation("添加商品")
    @ApiOperationSupport(order = 100)
    @PostMapping("/product/add")
    public JsonResult addProduct(@Validated AddProductDTO addProductDTO) {
        productService.add(addProductDTO);
        return JsonResult.ok(addProductDTO);
    }

    /**
     * @param httpServletRequest 公共接口类HttpServletRequest继承自ServletRequest。客户端浏览器发出的请求被封装成为一个HttpServletRequest对象。
     *                           对象包含了客户端请求信息包括请求的地址，请求的参数，提交的数据，上传的文件客户端的ip甚至客户端操作系统都包含在其内。
     *                           HttpServletResponse继承了ServletResponse接口，并提供了与Http协议有关的方法，这些方法的主要功能是设置HTTP状态码和管理Cookie。
     *                           Multipartfile spring框架中,最适合用于文件上传的接口,继承InputStreamSource
     *                           param
     */
    @ApiOperation("上传图片")
    @ApiOperationSupport(order =101)
    @PostMapping("/upload/file")
    public JsonResult upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) {
        //        获得原始名字
        String fileName = file.getOriginalFilename();
//        获得后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        生成UUID文件名
        UUID uuid = UUID.randomUUID();
//        拼接UUID和后缀名,生成新的文件名,
        String newFileName = uuid.toString() + suffixName;
//        创建文件,首先要有个文件夹,传入文件上传的地址
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new ServiceException(State.ERR,"文件夹创建失败");
            }
        }
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return JsonResult.ok(getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/images/" + newFileName);
        } catch (URISyntaxException e) {
            return JsonResult.fail(State.ERR,"文件上传失败");
        }
    }
    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                    null, null, null);
        } catch (URISyntaxException e) {
            effectiveURI = null;
        }
        return effectiveURI;
    }

    @ApiOperation("后台更新商品")
    @ApiOperationSupport(order = 102)
    @PostMapping("/product/update")
    public JsonResult updateProduct(@Validated UpdateProductDTO updateProductDTO) {
        //创建需要修改的实体类对象,这里是VO类
        Product product = new Product();
        BeanUtils.copyProperties(updateProductDTO,product);
        productService.update(product);
        return JsonResult.ok(updateProductDTO);
    }

    @ApiOperation("后台删除商品")
    @ApiOperationSupport(order = 103)
    @PostMapping("/product/delete")
    public JsonResult deleteProduct(@RequestParam Integer id) {
        productService.delete(id);
        return JsonResult.ok();
    }

    @ApiOperation("后台批量上下架")
    @ApiOperationSupport(order = 104)
    @PostMapping("/product/batchUpdateSellStatus")
    public JsonResult batchUpdateSellStatus(@RequestParam Integer[] ids,@RequestParam Integer sellStatus) {
        productService.batchUpdateSellStatus(ids,sellStatus);
        return JsonResult.ok();
    }

    @ApiOperation("后台商品列表")
    @ApiOperationSupport(order = 105)
    @GetMapping("/product/list")
    public JsonResult list(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        PageInfo pageInfo = productService.listForAdmin(pageNum, pageSize);
        return JsonResult.ok(pageInfo);
    }
}
